<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !cardInfo.visible &&
        !detailsInfo.visible &&
        !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-merge>
            <el-button
              :disabled="!canMerge"
              @click="handelMethodMerge(undefined)"
              >合单</el-button
            >
          </template>
          <template v-slot:filter-retract>
            <el-button :disabled="!canRetract" @click="retract()"
              >撤回</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-sumQty="scope">
          <span
            >{{ $fn.qtyFormatter(scope.row.sumStorageQty) }}/{{
              $fn.qtyFormatter(scope.row.sumQty)
            }}</span
          >
        </template>
      </table-container>
    </div>
    <use-application-details
      v-if="detailsInfo.visible"
      v-model:visible="detailsInfo.visible"
      @returnBack="getList"
      :title="detailsInfo.title"
      :id="detailsInfo.id"
    />
    <!-- 新增或修改 -->
    <UseApplicationModify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
      :id="modifyInfo.id"
    />
    <!-- 购物车新增 -->
    <CardAdd
      v-if="cardInfo.visible"
      v-model:visible="cardInfo.visible"
      @returnModify="returnCardModify"
      :id="cardInfo.id"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="useApplicationOrder">
import {
  getUseApplicationCustomizeList,
  deleteUseApplication,
  submitUseApplication,
  retractUseApplication,
  useApplicationMerge,
  useApplicationSplit,
} from '@/api/use'
const UseApplicationModify = defineAsyncComponent(() => import('./modify'))
const UseApplicationDetails = defineAsyncComponent(() => import('./details'))
const detailList = defineAsyncComponent(() => import('./detailList'))
const CardAdd = defineAsyncComponent(() => import('./cardAdd'))
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const ids = ref([])
const clearType = ref(true)
const slipSelectRequest = ref(true)
const time = ref([])

// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('useApplication:add'),
    },
    {
      type: 'button',
      label: '购物车新增',
      event: cartAdd,
      show: proxy.$permission('useApplication:cartAdd'),
    },
    {
      type: 'slot',
      value: 'merge',
      show: proxy.$permission('useApplicationOrder:merge'),
    },
    {
      type: 'slot',
      label: '撤回',
      value: 'retract',
      show: proxy.$permission('useApplication:retract'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('useApplication:update'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('useApplication:submit'),
        ifRender(row) {
          return row.status === 1 //待提交
        },
      },
      {
        label: '撤回',
        event: retract,
        show: proxy.$permission('useApplication:retract'),
        ifRender(row) {
          return row.status === 2 //待审核
        },
      },

      {
        label: '删除',
        event: _delete,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('useApplication:del'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '拆单',
        event: (row) => handelMethodSplit(row),
        show: proxy.$permission('useApplicationOrder:split'),
        ifRender: function (row) {
          return (
            (row.status === 1 || row.status === 2) &&
            row.mergedOrders.length > 0 &&
            row.status === row.beforeMergeStatus
          )
        },
      },
    ],
  },
})
//新增或更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
})
// 购物车新增
const cardInfo = reactive({
  visible: false,
  id: '',
})
const detailsInfo = reactive({
  visible: false,
  title: '',
  id: '',
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})

watch(
  () => filterInfo.query.applicationTimeGreater,
  (val) => {
    if (!val) {
      time.value = null
    }
  }
)

const canSubmit = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((row) => row.status !== 1).length === 0
  )
})
const canRetract = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((row) => row.status !== 2).length === 0
  )
})
const canMerge = computed(() => {
  return (
    tableInfo.selections.filter(
      (item) => item.status === 1 || item.status === 2
    ).length > 1
  )
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'useApplicationOrder' && el.url === val.url) {
                detailsInfo.visible = false
                modifyInfo.visible = false
                cardInfo.visible = false
                advancedSearchInfo.visible = false
                preferenceInfo.visible = false
                detailListInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailsInfo.visible = true
                  detailsInfo.id = val.businessId
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
watch(
  () => proxy.$router,
  (route) => {
    if (
      route &&
      route.currentRoute &&
      route.currentRoute.value &&
      route.currentRoute.value.name === 'useApplicationOrder'
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)
let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'use_application_status',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function handelMethodSplit(row = undefined) {
  const ids = getSelectionIds(row)
  useApplicationSplit(ids).then((resp) => {
    if (resp.success) {
      tableInfo.refresh = Math.random()
    }
  })
}
function handelMethodMerge(row = undefined) {
  const ids = getSelectionIds(row)
  useApplicationMerge(ids).then((resp) => {
    if (resp.success) {
      tableInfo.refresh = Math.random()
    }
  })
}
function getSelectionIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map(function (item) {
      return item.id
    })
  }
  return ids
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
function returnCardModify() {
  if (cardInfo.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'use_application_order',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'multDepotAuth',
    },
    // {
    //   asTbName: 'use_application_order',
    //   columnName: 'export_depot_id',
    //   queryType: 'IN',
    //   queryCategory: 'AND',
    //   value: 'multDepotAuth',
    // },
    // {
    //   asTbName: 'use_application_order',
    //   columnName: 'depot_rule_ids',
    //   queryType: 'IN',
    //   queryCategory: 'AND',
    //   value: 'multDepotAuth',
    // },
  ]
  let str = proxy.$store.state.permission.systemConfig.use_application_auth_type
  if (str == 1) {
    arr = [
      {
        asTbName: 'use_application_order',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'multDeptAuth',
      },
      // {
      //   asTbName: 'use_application_order',
      //   columnName: 'export_dept_id',
      //   queryType: 'IN',
      //   queryCategory: 'AND',
      //   value: 'multDeptAuth',
      // },
      // {
      //   asTbName: 'use_application_order',
      //   columnName: 'dept_rule_ids',
      //   queryType: 'IN',
      //   queryCategory: 'AND',
      //   value: 'multDeptAuth',
      // },
    ]
  }
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 创建
function create() {
  modifyInfo.id = null
  modifyInfo.visible = true
  modifyInfo.title = '新增领用单'
}
function cartAdd() {
  cardInfo.id = null
  cardInfo.visible = true
}
// 编辑
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.id = row.id
  modifyInfo.visible = true
  modifyInfo.title = '修改领用单'
}
// 查看明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailsInfo.id = row.id
  detailsInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 删除
function _delete(row) {
  const data = []
  data.push(row.id)
  deleteUseApplication(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
//提交
function submit(row = undefined) {
  const ids = getIds(row)
  submitUseApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//撤回
function retract(row = undefined) {
  const ids = getIds(row)
  retractUseApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((row) => row.id)
  }
  return ids
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.query.applicationTimeGreater = val[0]
    filterInfo.query.applicationTimeLess = val[1]
  } else {
    filterInfo.query.applicationTimeGreater = ''
    filterInfo.query.applicationTimeLess = ''
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(val = true) {
  let param = {
    tableKey:
      'useApplicationOrderIndex-com.slip.spd.entity.vo.use.UseApplicationOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let queryMap = {
        depotAuth: {
          asTbName: 'use_application_order',
          columnName: 'depot_id',
          queryType: 'IN',
          queryCategory: 'OR',
          value: 'multDepotAuth',
        },
        // exportDepotAuth: {
        //   asTbName: 'use_application_order',
        //   columnName: 'export_depot_id',
        //   queryType: 'IN',
        //   queryCategory: 'OR',
        //   value: 'multDepotAuth',
        // },
        // depotRuleIdsDeptAuth: {
        //   asTbName: 'use_application_order',
        //   columnName: 'depot_rule_ids',
        //   queryType: 'IN',
        //   queryCategory: 'OR',
        //   value: 'multDepotAuth',
        // },
      }
      let str =
        proxy.$store.state.permission.systemConfig.use_application_auth_type
      if (str == 1) {
        queryMap = {
          deptAuth: {
            asTbName: 'use_application_order',
            columnName: 'dept_id',
            queryType: 'IN',
            queryCategory: 'OR',
            value: 'multDeptAuth',
          },
          // exportDeptAuth: {
          //   asTbName: 'use_application_order',
          //   columnName: 'export_dept_id',
          //   queryType: 'IN',
          //   queryCategory: 'OR',
          //   value: 'multDeptAuth',
          // },
          // deptRuleIdsDeptAuth: {
          //   asTbName: 'use_application_order',
          //   columnName: 'dept_rule_ids',
          //   queryType: 'IN',
          //   queryCategory: 'OR',
          //   value: 'multDeptAuth',
          // },
        }
      }
      filterInfo.query.queryMap = {
        ...queryMap,
        ...searchInfo.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = val
      tableInfo.api = getUseApplicationCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
